package com.itheima.core.web.controller;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.itheima.core.po.*;
import com.itheima.core.service.RoleRightService;
import com.itheima.core.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Controller
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRightService roleRightService;

    @RequestMapping("role/role.action")
    public String list(Model model) {
        List<Role> allRole = roleService.findAllRole();
        // 添加参数
        model.addAttribute("roles", allRole);
        return "role";
    }
    @RequestMapping("role/right.action")
    public String rightList(Model model) {
        return "right";
    }

    @RequestMapping("role/getZtree.action")
    @ResponseBody
    public List getRoleZtree(Integer id) {
        List<RoleRight> zTree = roleRightService.findZtree();

        String[] checked = roleRightService.findChecked(id);
        for (RoleRight roleRight : zTree) {
            if(Arrays.asList(checked).contains(roleRight.getId())){
                roleRight.setChecked(true);
            }
        }
        return zTree;
    }
    @RequestMapping("role/saveRoleRight.action")
    @ResponseBody
    public String saveRoleRight(Integer id,String rights) {
        String[] rightss = rights.split(",");
        Integer integer = roleRightService.clearRight(id);
        Integer integer1 = roleRightService.saveRoleRight(id, rightss);
        if(integer1>0){
            return "OK";
        }else{
            return "False";
        }

    }
    /*
    * 查找所有功能节点
    * */
    @RequestMapping("right/finAllFunctionNodes.action")
    @ResponseBody
    public List getFunctionNodes() {
        List<RoleRight> allFunctionNodes = roleRightService.findAllFunctionNodes();
        return allFunctionNodes;
    }
    /*
    * 根据id加载功能模块页面
    * */

    @RequestMapping("right/findFunctionById.action")
    public String findFunctionById(Model model,String id) {
        Function functionById = roleRightService.findFunctionById(id);
        List<Function> submoduleById = roleRightService.findSubmoduleById(id);
        List<FunctionRight> functionRightById = roleRightService.findFunctionRightById(id);
        // 添加参数
        model.addAttribute("functionById",functionById);
        model.addAttribute("submoduleById",submoduleById);
        model.addAttribute("functionRightById",functionRightById);
        return "function";
    }
}
